﻿using System;
using System.Data.SqlServerCe;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using SenseTimeTracker.BusinessLayer;
using SenseTimeTracker.Main;
using SenseTimeTracker.Misc;
using SenseTimeTracker.Properties;
using StedySoft.SenseSDK;
using StedySoft.SenseSDK.DrawingCE;

namespace SenseTimeTracker.Users
{
	public class UsersSliderPanel : CommonSliderPanel<User>
	{
		public UsersSliderPanel(SenseTimeTrackerForm form)
			: base(form, "UserSmallIcon.png", "UserLargeIcon.png", MenuEnty.New | MenuEnty.Edit | MenuEnty.Remove)
		{
			sorting = Persistance.Instance.UsersSorting;
			sortColumns = SortColumn.Name;
		}

		public override string Name { get { return Resources.PanelUsersName; } }

		protected override void MenuItemNewEntry_Click(object sender, EventArgs e)
		{
			using (new DialogHelper(ownedForm))
			{
				UserEditForm form = new UserEditForm
				{
					User = new User(),
				};
				if (form.ShowDialog() == DialogResult.OK)
				{
					form.User.Insert();
					form.PersistWorkingTime();
					Bind(senseListControl);
				}
			}
		}

		protected override void MenuItemEditEntry_Click(object sender, EventArgs e)
		{
			using (new DialogHelper(ownedForm))
			{
				UserDisplayItem item = senseListControl.FocusedItem as UserDisplayItem;
				if (item != null)
				{
					UserEditForm form = new UserEditForm
					{
						User = User.GetUser(item.UserId),
					};
					if (form.ShowDialog() == DialogResult.OK)
					{
						form.User.Update();
						form.PersistWorkingTime();
						Bind(senseListControl);
					}
				}
			}
		}

		protected override void MenuItemRemoveEntry_Click(object sender, EventArgs e)
		{
			if (SenseAPIs.SenseMessageBox.Show(Resources.DialogDeleteQuestion, Resources.DialogHeaderRemoveUser, SenseMessageBoxButtons.YesNo) == DialogResult.Yes)
			{
				UserDisplayItem userItem = senseListControl.FocusedItem as UserDisplayItem;
				User.Delete(userItem.UserId);
				Bind(senseListControl);
			}
		}

		public override void Bind(SenseListControl senseListControl)
		{
			base.Bind(senseListControl);
			senseListControl.AddItem(new SensePanelDividerItem(string.Empty, Resources.UsersExplanation));
			var filteredUsers = from user in User.Users select user;
			SortFilter(ref filteredUsers);
			foreach (User user in filteredUsers)
			{
				senseListControl.AddItem(new UserDisplayItem
				{
					UserId = user.Id,
					UserName = user.Name,
				});
			}
		}

		public override void BindFilter()
		{
			BindFilter(Resources.UsersFilterHeader);
		}
	}
}
